﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Controls;
using System.Windows.Media;

namespace System.Windows.Controls
{
    public static class MediaElementExtensions
    {
        #region 背景视频

        /// <summary>
        /// 将媒体播放器作为背景视频
        /// </summary>
        /// <param name="media"></param>
        /// <param name="videoSource"></param>
        public static void AsBackground(this MediaElement media, string videoSource)
        {
            media.ScrubbingEnabled = true;
            media.IsMuted = true;
            media.Stretch = Stretch.Fill;
            var mtl = new MediaTimeline(new Uri(videoSource, UriKind.Absolute));
            media.Clock = mtl.CreateClock();
            media.Clock.CurrentTimeInvalidated += Clock_CurrentTimeInvalidated1;
            media.Clock.Completed += Clock_Completed;
            media.Clock.Controller.Begin();
        }


        private static void Clock_Completed(object sender, EventArgs e)
        {
            var mc = (MediaClock)sender;
            mc.Controller.Seek(TimeSpan.FromMilliseconds(80), System.Windows.Media.Animation.TimeSeekOrigin.BeginTime);
        }

        private static void Clock_CurrentTimeInvalidated1(object sender, EventArgs e)
        {
            var mc = (MediaClock)sender;
            var ct = mc.CurrentTime;
            if (mc.NaturalDuration.HasTimeSpan && mc.NaturalDuration.TimeSpan - ct < TimeSpan.FromMilliseconds(80))
            {
                mc.Controller.Seek(TimeSpan.FromMilliseconds(80), System.Windows.Media.Animation.TimeSeekOrigin.BeginTime);
            }
        }
        #endregion
        /// <summary>
        /// 作为循环播放的音乐播放器
        /// </summary>
        /// <param name="media"></param>
        /// <param name="audioSource"></param>
        public static void AsLoopSoundPlayer(this MediaElement media, string audioSource)
        {
            media.Source = new Uri(audioSource, UriKind.Absolute);
            media.IsMuted = false;
            media.Visibility = Visibility.Collapsed;
            media.Volume = 1;
            media.LoadedBehavior = MediaState.Manual;
            media.UnloadedBehavior = MediaState.Manual;
            media.MediaEnded += Media_MediaEnded;
            media.Play();
        }

        private static void Media_MediaEnded(object sender, RoutedEventArgs e)
        {
            ((MediaElement)sender).Stop();
            ((MediaElement)sender).Play();
        }
         
    }
}
